//
//  YSGWesternSearchController.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2022/7/1.
//  Copyright © 2022 QDSG. All rights reserved.
//

import UIKit

class YSGWesternSearchController: BaseViewController {

    let viewModel: YSGWesternSearchViewModel = YSGWesternSearchViewModel()
    
    var page :Int = 0
    
    @IBOutlet weak var searchTextField: UITextField!{
        didSet{
            searchTextField.leftViewMode = .always
            searchTextField.leftView = searchView
        }
    }
    
    lazy var searchView : UIView =  {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 45, height: 30))
        let imageView = UIImageView(image: UIImage(named: "search"))
        imageView.frame = CGRect(x: 20, y: 7.5, width: 15, height: 15)
        view.addSubview(imageView)
        return view
    }()
    @IBOutlet weak var tableView: UITableView!{
        didSet{
            tableView.mj_header = refreshHeader(action: #selector(loadData))
            tableView.mj_footer = refreshFooter(action: #selector(loadMore))
            tableView.register(YSGWesternSearchListCell.nibForCell(),
                               forCellReuseIdentifier: YSGWesternSearchListCell.reuseIdentifier())
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "互联网药品目录"
        
        tableView.mj_header?.beginRefreshing()
    }

    @objc func loadData(){
        page = 0
        getWesternSearchList()
    }
    @objc func loadMore(){
        page = page + 1
        getWesternSearchList()
    }
    func getWesternSearchList(){
        viewModel.getWesternSearchList(page: page, keyWords: searchTextField.text ?? "") {[weak self] in
            self?.tableView.mj_header?.endRefreshing()
            self?.tableView.mj_footer?.endRefreshing()
            self?.tableView.reloadData()
        }
    }
    
    @IBAction func searchWordEndAction(_ sender: Any) {
        tableView.mj_header?.beginRefreshing()
    }
    

    
}
extension YSGWesternSearchController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return viewModel.searchList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YSGWesternSearchListCell.reuseIdentifier(), for: indexPath) as! YSGWesternSearchListCell
        cell.configure(with: viewModel.searchList[indexPath.row])
        return cell
    }
    
  
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 87
    }
    

    


    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    
    }
}
